// ==UserScript==
// @name         getOrgsListFromOUsite
// @namespace    http://tampermonkey.net/
// @version      0.7
// @description  try to take over the world!
// @author       Xenon_x
// @match        https://uo-tashtagol.3dn.ru/index/sistema_obrazovanija_municipaliteta/0-244
// @icon         https://www.google.com/s2/favicons?domain=3dn.ru
// @grant        none
// @require https://unpkg.com/export-from-json
// ==/UserScript==

window.addEventListener("load", () => {
    loader.importJS('https://unpkg.com/export-from-json');
    $(".docs > section")
      .eq(0)
      .prepend(
        '<a href="#" onclick="exportOrgList()" style="justify-content: end;">Скачать список ОУ+Сайт URL</a>'
      );
  });
  window.exportOrgList = function () {
    "use strict";
  
    let orgList = {};
    let org_parse = (org, orgCat) => {
      let rName = org.innerText;
      let name = rName.match(/^[^(]+(?=\()/);
      name = name ? name[0].trim() : rName;
      let args = rName.match(/(?<=\()([\W\d]*?)(?=\))/g);
      let oTypes = [
        "МБУ",
        "МКУ",
        "МБОУ",
        "МКОУ",
        "МОУ",
        "МАДОУ",
        "МБДОУ",
        "МАОУ",
        "МКДОУ",
      ];
      let [inn, ogrn, sName] = Array(3).fill("-");
      if (args) {
        for (let arg of args) {
          inn = arg.toLowerCase().includes("инн")
            ? arg.toLowerCase().match(/(?<=инн\W?\s*)([0-9])+/g)[0]
            : inn;
          ogrn = arg.toLowerCase().includes("огрн")
            ? arg.toLowerCase().match(/(?<=огрн\W?\s*)([0-9])+/g)[0]
            : ogrn;
          sName = oTypes.some((t) => arg.includes(t)) ? arg : sName;
        }
      }
      orgList[orgCat].push({
        name: name,
        shortName: sName,
        url: org.href,
        inn: inn,
        ogrn: ogrn,
      });
    };
    let t = [
      $(".docs section:first .splLink"),
      $(".docs section:first .splCont"),
    ];
    t.forEach((s) => {
      if (s.eq(0)[0].classList.contains("splLink"))
        s.each((i, t) => (orgList[t.innerText] = []));
      if (s.eq(0)[0].classList.contains("splCont"))
        s.each((i, c) => {
          c.querySelectorAll("[id*=orgs_] a").forEach( o =>{
  let orgCat =
            Object.keys(orgList)[
              c.querySelector("[id*=orgs_]").id.substr(-1) - 1
            ];
   org_parse(o, orgCat);
        });
        });
    });
    //add dd in unknow cat
    orgList['Unknow'] = []
    $(".docs #orgs_4 a").each((i,o) => {
      let orgCat = "Unknow";
      org_parse(o, orgCat);
    });
    //post processing
    orgList["Дошкольное образование"] = orgList["Дошкольное образование"].map(
      (o) => {
        return {
          name: o.name,
          shortName: o.shortName,
          url: o.url,
          inn: o.inn,
          ogrn: o.ogrn,
        };
      }
    );
    let tableTitle = [
      "Наименование ОУ",
      "Сокращенное наименование ОУ",
      "Адрес сайта",
      "ИНН",
      "ОГРН",
    ];
    orgList = [
      tableTitle,
      ...Object.values(orgList)
        .map((m) => m.map((o) => [o.name, o.shortName, o.url, o.inn, o.ogrn]))
        .reduce((ma, m) => ma.concat(m))
        .filter((e) => e[0]),
    ];
    console.log(orgList);
    exportFromJSON({
      data: orgList,
      fileName: "orgList",
      exportType: exportFromJSON.types.xls,
    });
    //types: txt, css, html, json, csv, xls, xml
  };
  